/*  Copyright 2010 princehaku
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Author     : princehaku
 */

package net.techest.httpproxy;

import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// Small, simple HTTP server
public class HTTPProxyServer {
	
	int serverPort;
	
	public HTTPProxyServer() {
		this.serverPort = 80;
	}
	
	public HTTPProxyServer(int port) {
		this.serverPort = port;
	}

	// Run until interrupted
	public void run() {
		try {
			// Get a server socket
			ServerSocket server = getServerSocket();
			int localPort = server.getLocalPort();
			// Let us know that you're listening
			System.out.println("listening on port " + localPort);
			//创建线程池
			ExecutorService pool = Executors.newFixedThreadPool(2); 
			
			do {
				// Accept a connection
				Socket client = server.accept();
				// Handle the connection with a separate thread
				System.out.println("New Thread Start");
				(new HTTPThread(client)).start();
			} while (true);
		} catch (Exception ex) {
			System.out.println("Unable to listen on " + serverPort + ".");
			ex.printStackTrace();
			System.exit(1);
		}
	}

	// Get a server socket on the hard-wired server port
	ServerSocket getServerSocket() throws Exception {
		return new ServerSocket(serverPort);
	}
}